package com.gitee.magic.jdbc.spring.context;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;

import com.gitee.magic.core.exception.ApplicationException;
import com.gitee.magic.jdbc.persistence.EntityDefinitionException;
import com.gitee.magic.jdbc.persistence.EntityFactory;
import com.gitee.magic.jdbc.persistence.EntityObject;
import com.gitee.magic.jdbc.persistence.annotation.Entity;
import com.gitee.magic.jdbc.persistence.support.DefaultEntityFactory;
import com.gitee.magic.jdbc.persistence.support.EntityDefinitionDelegate;

/**
 * @author start
 */
public class PersistenceEntityRegistryPostProcessor implements BeanFactoryPostProcessor {

	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

		EntityFactory entityFactory=new DefaultEntityFactory();
		String[] names=beanFactory.getBeanNamesForAnnotation(Entity.class);
		
		for(String name:names){
			Class<?> prototype=beanFactory.getType(name);
			try {
				EntityObject object=EntityDefinitionDelegate.parse(prototype);
				entityFactory.registerEntityDefinition(object);
			} catch (EntityDefinitionException e) {
				throw new ApplicationException(e);
			}
		}
		
		//添加处理器
		beanFactory.addBeanPostProcessor(new EntityFactoryContextAwareProcessor(beanFactory,entityFactory));
		
	}

}
